from article_app.models import Article
from user_app.models import User
from django_filters import rest_framework as filters

class ArticleFilter(filters.FilterSet):
    #method后跟的函数表示自定义筛选
    # sort = filters.OrderingFilter(fields=('add_time', 'view_no'))
    title = filters.CharFilter(method='title_filter', label="title")
    author = filters.CharFilter(method='author_filter', label="u_id")
    content_text = filters.CharFilter(method='content_text_filter', label="content_text")
    tags = filters.CharFilter(method='tags_filter', label="tags")
    is_check_eq = filters.NumberFilter(field_name='is_check', lookup_expr="exact")

    def author_filter(self, queryset, name, value):
         return queryset.filter(u_id__nick_name__icontains=value)

    def title_filter(self, queryset, name, value):
         return queryset.filter(title__icontains=value)
    
    def content_text_filter(self, queryset, name, value):
         return queryset.filter(content_text__icontains=value)
 
    def tags_filter(self, queryset, name, value):
        return queryset.filter(tags__icontains=value)
    
    class Meta:
        model = Article
        fields = ("tags", "author", "content_text", "is_check_eq", "title")
        order_by_field = 'order'
        order_by = ('id',)
        
        
class UserFilter(filters.FilterSet):
    #method后跟的函数表示自定义筛选
    # sort = filters.OrderingFilter(fields=('add_time', 'view_no'))
    nick_name = filters.CharFilter(method='nick_name_filter', label="nick_name")
    email = filters.CharFilter(method='email_filter', label="email")
    info = filters.CharFilter(method='info_filter', label="info")

    def nick_name_filter(self, queryset, name, value):
         return queryset.filter(nick_name__icontains=value)
    
    def email_filter(self, queryset, name, value):
          return queryset.filter(email__icontains=value)

    def info_filter(self, queryset, name, value):
         return queryset.filter(info__icontains=value)
    
    class Meta:
        model = User
        fields = ("nick_name", "info", "email")
